package unclevenn.cloudmusic.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import unclevenn.cloudmusic.common.Response;
import unclevenn.cloudmusic.until.MinioUntil;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("file")
public class FileUpload {

    @Autowired
    private MinioUntil minioUntil;

    @PostMapping("/upload")
    public JSONObject upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return Response.error("请选择文件!");
        }
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String objectName = DigestUtils.md5DigestAsHex((fileName + System.currentTimeMillis()).getBytes());
        minioUntil.makeBucket(fileType);
        minioUntil.putObject(fileType, objectName + "." + fileType, file.getInputStream(), contentType);
        Map<String, String> map = new HashMap<>();
        map.put("objectName", objectName);
        return Response.success(map);
    }
}
